import Dwarf.DwarfSimulator;
import Dwarf.DwarfType;
import java.io.*;

public class DwarfInterpreter
{
    private DwarfSimulator dwarfSimulator;
    private Parser parser;

    public DwarfInterpreter(DwarfType dwarfType)
    {
        dwarfSimulator = new DwarfSimulator(dwarfType);
        parser = new Parser();
    }

    public void HandleFile(File file)
    {
        try
        {
            FileInputStream fInStream = new FileInputStream(file);
            DataInputStream dataInputStream = new DataInputStream(fInStream);
            BufferedReader br = new BufferedReader(new InputStreamReader(dataInputStream));

            String codeLine;
            while ((codeLine = br.readLine()) != null)
            {
                HandleCodeLine(codeLine);
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }

    public void HandleCodeLine(String codeLine)
    {
        try
        {
            SyntaxNode syntaxTree = parser.Parse(codeLine);
            RunNode(syntaxTree);
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }

    private void RunNode(SyntaxNode node)
    {
        if (node != null)
        {
            if (node.type == SyntaxNodeType.WHILE)
            {
                String conditionVariable = node.operand1.value;
                while (dwarfSimulator.ConditionIsTrue(conditionVariable))
                {
                    RunNode(node.operand2);
                }
            }
            else if (node.type == SyntaxNodeType.COMMAND)
            {
                dwarfSimulator.ExecuteCommand(node.value);
            }
            else
            {
                RunNode(node.operand1);
                RunNode(node.operand2);
            }
        }
    }

}
